package view.panel;

import javax.swing.*;

import bean.User;
import dao.EmployeeDAO;
import dao.UserDAO;
import tool.DisableEditTableModel;

import java.awt.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Vector;

public class UserPanel extends JPanel {
    private static final long serialVersionUID = -8982909495535339826L;
    private UserDAO userDAO;
    private EmployeeDAO employeeDAO;
    private int userId;
    private Dimension dimension;
    private JPanel leftPanel;
    private JScrollPane scrollPane;
    private JTable table;
    private DisableEditTableModel tableModel;
    private JPanel southPanel;
    private JButton refreshButton;
    private JButton editAccountButton;
    private JButton addAccountButton;
    private JButton deleteAccountButton;
    private JPanel rightPanel;
    private JPanel panel1, panel2, panel3, panel4, panel5, panel6, panel7;
    private JTextField userIdTextField;
    private JTextField userNameTextField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private Hashtable<Integer, String> statusData;
    private Set<Map.Entry<Integer, String>> statusEntry;
    private JComboBox<String> statusComboBox;
    private DefaultComboBoxModel<String> comboBoxModel;
    private JTextField employeeIdTextField;
    private JButton submitButton;

    public UserPanel(Connection conn) throws SQLException {
        super(new BorderLayout());
        userDAO = new UserDAO(conn);
        employeeDAO = new EmployeeDAO(conn);
        setName("用户管理");
        add(new JPanel(new BorderLayout()), BorderLayout.CENTER);
        add(new JPanel(new GridLayout(7, 1)), BorderLayout.EAST);
        initializeComboBox();
        table = new JTable();
        tableModel = new DisableEditTableModel();
        tableModel.setDataVector(rowsData(), columnNames());
        table.setModel(tableModel);
        scrollPane = new JScrollPane(table);
        leftPanel = (JPanel) getComponent(0);
        leftPanel.add(scrollPane, BorderLayout.CENTER);
        southPanel = new JPanel();
        refreshButton = new JButton("刷新");
        refreshButton.addActionListener(actionEvent -> {
            try {
                tableModel.setDataVector(rowsData(), columnNames());
                userIdTextField.setText(null);
                userNameTextField.setText(null);
                userNameTextField.setEnabled(true);
                statusComboBox.setEnabled(true);
                employeeIdTextField.setText(null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
        southPanel.add(refreshButton);
        editAccountButton = new JButton("编辑用户");
        editAccountButton.addActionListener(actionEvent -> {
            int length = table.getSelectedRows().length;
            if (length == 1) {
                int rowIndex = table.getSelectedRow();
                int userId = (int) tableModel.getValueAt(rowIndex, 0);
                try {
                    User user = userDAO.selectById(userId);
                    userIdTextField.setText(String.valueOf(userId));
                    userNameTextField.setText(user.getUserName());
                    userNameTextField.setEnabled(false);
                    int status = user.getStatus();
                    for (Map.Entry<Integer, String> entry : statusEntry) {
                        if (entry.getKey() == status) {
                            statusComboBox.setSelectedItem(entry.getValue());
                            break;
                        }
                    }
                    int count = userDAO.selectUidCountByUi(status);
                    // 当编辑的用户为当前登录用户并且此身份在用户数据库表中只有一条记录
                    if (userId == getUserId() && count == 1) {
                        statusComboBox.setEnabled(false);
                    } else {
                        statusComboBox.setEnabled(true);
                    }
                    employeeIdTextField.setText(String.valueOf(user.getEmployeeId()));
                    employeeIdTextField.setEnabled(false);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        southPanel.add(editAccountButton);
        addAccountButton = new JButton("添加用户");
        addAccountButton.addActionListener(actionEvent -> {
            table.clearSelection();
            userNameTextField.setEnabled(true);
            userIdTextField.setText(null);
            userNameTextField.setText(null);
            passwordField.setText(null);
            confirmPasswordField.setText(null);
            statusComboBox.setSelectedIndex(0);
            statusComboBox.setEnabled(true);
            employeeIdTextField.setText(null);
            employeeIdTextField.setEnabled(true);
        });
        southPanel.add(addAccountButton);
        deleteAccountButton = new JButton("删除用户");
        deleteAccountButton.addActionListener(actionEvent -> {
            userIdTextField.setText(null);
            userNameTextField.setText(null);
            userNameTextField.setEnabled(true);
            int[] rows = table.getSelectedRows();
            try {
                if (rows.length > 0) {
                    int status = JOptionPane.showConfirmDialog(null, "确定要删除选中的用户吗？此操作不可逆。", "确认删除", JOptionPane.YES_NO_OPTION);
                    if (status == 0) {
                        // 倒序删除用户
                        for (int rowIndex = rows.length - 1; rowIndex > -1; rowIndex--) {
                            int userId = (int) tableModel.getValueAt(rows[rowIndex], 0);
                            // 如果预删除的指定用户编号不是登录的用户编号
                            if (userId != getUserId()) {
                                // 从数据库表中删除指定用户
                                userDAO.delete(userId);
                                tableModel.removeRow(rows[rowIndex]);
                            }
                        }
                        JOptionPane.showMessageDialog(null, "除已登录的用户信息不能被删除外，其他用户信息均可以被删除");
                    }
                }
                tableModel.setDataVector(rowsData(), columnNames());
                statusComboBox.setEnabled(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
        southPanel.add(deleteAccountButton);
        leftPanel.add(southPanel, BorderLayout.SOUTH);
        rightPanel = (JPanel) getComponent(1);
        add(rightPanel, BorderLayout.EAST);
        rightPanel.add(new JPanel());
        rightPanel.add(new JPanel());
        rightPanel.add(new JPanel());
        rightPanel.add(new JPanel());
        rightPanel.add(new JPanel());
        rightPanel.add(new JPanel());
        rightPanel.add(new JPanel());
        dimension = new Dimension(83, 22);
        panel1 = (JPanel) rightPanel.getComponent(0);
        panel1.add(new JLabel("用户编号"));
        userIdTextField = new JTextField();
        userIdTextField.setEnabled(false);
        userIdTextField.setPreferredSize(dimension);
        panel1.add(userIdTextField);
        panel2 = (JPanel) rightPanel.getComponent(1);
        panel2.add(new JLabel("用户名称"));
        userNameTextField = new JTextField();
        userNameTextField.setPreferredSize(dimension);
        panel2.add(userNameTextField);
        panel3 = (JPanel) rightPanel.getComponent(2);
        panel3.add(new JLabel("用户密码"));
        passwordField = new JPasswordField();
        passwordField.setPreferredSize(dimension);
        panel3.add(passwordField);
        panel4 = (JPanel) rightPanel.getComponent(3);
        panel4.add(new JLabel("确认用户密码"));
        confirmPasswordField = new JPasswordField();
        confirmPasswordField.setPreferredSize(dimension);
        panel4.add(confirmPasswordField);
        panel5 = (JPanel) rightPanel.getComponent(4);
        panel5.add(new JLabel("用户身份"));
        statusComboBox = new JComboBox<>();
        statusComboBox.setPreferredSize(dimension);
        statusComboBox.setModel(comboBoxModel);
        panel5.add(statusComboBox);
        panel6 = (JPanel) rightPanel.getComponent(5);
        panel6.add(new JLabel("用户关联员工编号"));
        employeeIdTextField = new JTextField();
        employeeIdTextField.setPreferredSize(dimension);
        panel6.add(employeeIdTextField);
        panel7 = (JPanel) rightPanel.getComponent(6);
        submitButton = new JButton("提交");
        submitButton.addActionListener(actionEvent -> {
            boolean enabled = userNameTextField.isEnabled();
            String password = String.valueOf(passwordField.getPassword());
            String confirmPassword = String.valueOf(confirmPasswordField.getPassword());
            boolean passwordRule = password.length() > 0 && confirmPassword.equals(password);
            String statusText = (String) statusComboBox.getSelectedItem();
            int status = 0;
            for (Map.Entry<Integer, String> entry : statusEntry) {
                if (entry.getValue().equals(statusText)) {
                    status = entry.getKey();
                    break;
                }
            }
            boolean state = false;
            if (!passwordRule) {
                JOptionPane.showMessageDialog(null, "用户密码不能为空且确认用户密码必须与前者一致");
            } else {
                User user = new User(password, status);
                try {
                    if (enabled) {
                        // 添加用户
                        String userName = userNameTextField.getText();
                        if (Objects.isNull(userName) || userName.length() == 0) {
                            JOptionPane.showMessageDialog(null, "用户名称不能为空");
                        } else {
                            user.setUserName(userName);
                            int employeeId = Integer.parseInt(employeeIdTextField.getText());
                            if (userDAO.selectIdByEmployeeId(employeeId) > 0) {
                                JOptionPane.showMessageDialog(null, "指定用户已关联目标员工编号");
                            } else {
                                user.setEmployeeId(employeeId);
                                state = userDAO.insert(employeeDAO, user);
                                if (state) {
                                    JOptionPane.showMessageDialog(null, "添加用户成功");
                                } else {
                                    JOptionPane.showMessageDialog(null, "添加用户失败");
                                }
                            }
                        }
                    } else {
                        // 编辑用户
                        int userId = Integer.parseInt(userIdTextField.getText());
                        user.setUserId(userId);
                        state = userDAO.update(user);
                        if (state) {
                            JOptionPane.showMessageDialog(null, "编辑用户成功");
                        } else {
                            JOptionPane.showMessageDialog(null, "编辑用户失败");
                        }
                    }
                    if (state) {
                        tableModel.setDataVector(rowsData(), columnNames());
                        userIdTextField.setText(null);
                        userNameTextField.setText(null);
                        userNameTextField.setEnabled(true);
                        passwordField.setText(null);
                        confirmPasswordField.setText(null);
                        statusComboBox.setSelectedIndex(0);
                        employeeIdTextField.setText(null);
                    }
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "用户关联员工编号必须是纯数字");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        panel7.add(submitButton);
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    private void initializeComboBox() {
        statusData = new Hashtable<>();
        statusData.put(0, "所有者");
        statusData.put(1, "收银员");
        statusData.put(2, "进货定价员");
        statusEntry = statusData.entrySet();
        Vector<String> items = new Vector<>();
        for (Map.Entry<Integer, String> entry : statusEntry) {
            items.addElement(entry.getValue());
        }
        comboBoxModel = new DefaultComboBoxModel<>(items);
    }

    private Vector<Vector<Object>> rowsData() throws SQLException {
        Vector<User> users = userDAO.selectAll();
        Vector<Vector<Object>> rowsData = new Vector<>();
        for (User user : users) {
            Vector<Object> rowData = new Vector<>();
            rowData.addElement(user.getUserId());
            rowData.addElement(user.getUserName());
            int status = user.getStatus();
            for (Map.Entry<Integer, String> entry : statusEntry) {
                if (entry.getKey() == status) {
                    rowData.addElement(entry.getValue());
                }
            }
            rowData.addElement(user.getEmployeeId());
            rowsData.addElement(rowData);
        }
        return rowsData;
    }

    private Vector<String> columnNames() {
        Vector<String> columnNames = new Vector<>();
        columnNames.addElement("用户编号");
        columnNames.addElement("用户名称");
        columnNames.addElement("用户身份");
        columnNames.addElement("用户关联员工编号");
        return columnNames;
    }
}
